package com.nolon.flange.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.nolon.flange.databinding.ItemFileBinding
import com.nolon.flange.model.FileItem
import com.nolon.flange.tools.toFriendlyDate

class FileAdapter(
    val onFileClicked: (FileItem) -> Unit,
    val onMoreClicked: (FileItem) -> Unit
) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val files = mutableListOf<FileItem>()

    fun swapData(files: List<FileItem>) {
        this.files.clear()
        this.files.addAll(files)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val binding = ItemFileBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return FileViewHolder(binding)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val file = files[position]
        if (holder is FileViewHolder) {
            with(holder.binding) {
                layout.setOnClickListener { onFileClicked(file) }
                textFileName.text = file.name
                textDigest.text = file.modifiedDate.toFriendlyDate
                imageMore.setOnClickListener { onMoreClicked(file) }
            }
        }
    }


    override fun getItemCount() = files.size

    class FileViewHolder(val binding: ItemFileBinding) : RecyclerView.ViewHolder(binding.root)


}